package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        //判断地址是否为空
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //根据用户id查询购物车 判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null && list.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //拷贝前端传递过来的请求参数
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //数据传输过程中被劫持(价格被修改)问题解决方法 重新计算金额
        BigDecimal amount = BigDecimal.valueOf(0);
        for (ShoppingCart cart : list) {
            if (cart.getDishId() != null){
                Dish dish = dishMapper.selectById(cart.getDishId());
                amount = amount.add(dish.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
            }else {
                Setmeal setmeal = setmealMapper.selectById(cart.getSetmealId());
                amount = amount.add(setmeal.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
            }
        }
        orders.setAmount(amount.add(BigDecimal.valueOf(ordersSubmitDTO.getPackAmount()+6)));
        //设置用户id
        orders.setUserId(BaseContext.getCurrentId());
        //设置手机号
        orders.setPhone(addressBook.getPhone());
        //设置收货人
        orders.setConsignee(addressBook.getConsignee());
        //设置详细地址
        orders.setAddress(addressBook.getDetail());
        //设置订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //生成订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//分库分表，id自增会重复 UUID无法排序
        //将数据插入订单表
        orderMapper.insert(orders);
        //批量插入  比依次插入更快
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //拷贝购物车数据至订单明细
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //将数据插入订单明细表
        orderDetailMapper.insertBatch(orderDetailList);
        //下单成功，清空购物车
        shoppingCartMapper.deleteByUserId(shoppingCart);
        //返回前端需要的数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public PageResult selectHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //分页查询订单表
        Page<Orders> ordersPage = orderMapper.selectOrdersPage(ordersPageQueryDTO);
        //查询每个订单的订单明细，取出数据封装到OrderVO返回前端
        List<OrderVO> list = new ArrayList();
        for (Orders orders : ordersPage) {
            //条件查询
            List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            list.add(orderVO);
        }
        return new PageResult(ordersPage.getTotal(), list);
    }

    @Override
    public OrderVO selectOrderDetail(Integer id) {
        //根据订单id查询订单表返回订单对象
        Orders orders = orderMapper.selectById(id);
        //根据订单id查询订单详情表返回订单详情对象集合
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void cancelOrders(Integer id) throws Exception {
        //取消订单时订单明细相关数据清空(查阅笔记得知)
        //根据id查询订单
        Orders orders = orderMapper.selectById(id);
        //校验订单是否存在
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果订单已被接受，则无法取消
        if (orders.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单在待接单状态下取消，直接退款(在待支付状态下直接取消)
        if (orders.getStatus() == 2){
            //     * @param outTradeNo    商户订单号
            //     * @param outRefundNo   商户退款单号
            //     * @param refund        退款金额
            //     * @param total         原订单金额
            weChatPayUtil.refund(orders.getNumber(),orders.getNumber(),orders.getAmount(),orders.getAmount());
            //将支付状态修改为已退款
            orders.setPayStatus(2);
        }
        //设置订单状态、取消原因、取消时间
        orders.setStatus(6);//已取消
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void repetitionOrders(Integer id) {
        //根据id查询订单
        Orders orders = orderMapper.selectById(id);
        //校验订单是否存在
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //用订单id在订单明细表中查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());
        //将订单明细对象中的数据传入购物车对象
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .name(orderDetail.getName())
                    .dishId(orderDetail.getDishId())
                    .setmealId(orderDetail.getSetmealId())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .number(orderDetail.getNumber())
                    .amount(orderDetail.getAmount())
                    .image(orderDetail.getImage())
                    .userId(BaseContext.getCurrentId())
                    .createTime(LocalDateTime.now())
                    .build();
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    @Override
    public PageResult selectOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //分页查询订单表
        Page<Orders> ordersPage = orderMapper.selectOrdersPage(ordersPageQueryDTO);
        //查询每个订单的订单明细，取出数据封装到OrderVO返回前端
        List<OrderVO> list = new ArrayList();
        for (Orders orders : ordersPage) {
            //条件查询
            List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());
            //订单包含的菜品以字符串形式表示
            List<String> orderDishList = orderDetailList.stream().map(x -> {
                String orderDish = x.getName() + "*" + x.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());
            //拼接字符串
            String orderDishes = String.join("", orderDishList);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDishes(orderDishes);
            list.add(orderVO);
        }
        return new PageResult(ordersPage.getTotal(), list);
    }

    @Override
    public OrderStatisticsVO statisticsByStatus() {
        //待派送数量
        Integer confirmed = orderMapper.countByStatus(Orders.CONFIRMED);
        //派送中数量
        Integer deliveryInProgress = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);
        //待接单数量
        Integer toBeConfirmed = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .toBeConfirmed(toBeConfirmed)
                .build();
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //根据id查询订单
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId().intValue());
        //只有当订单存在且处于待接单状态才能拒单
        if (orders == null || orders.getStatus() != 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //如果已付款则需退款
        if (orders.getPayStatus() == 1){
            weChatPayUtil.refund(orders.getNumber(),orders.getNumber(),orders.getAmount(),orders.getAmount());
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //根据id查询订单
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId().intValue());
        //如果已付款则需退款
        if (orders.getPayStatus() == 1){
            weChatPayUtil.refund(orders.getNumber(),orders.getNumber(),orders.getAmount(),orders.getAmount());
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Integer id) {
        //根据id查询订单
        Orders orders = orderMapper.selectById(id);
        //当订单存在且状态为已接单时才可派送
        if (orders == null || orders.getStatus() != 3){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Integer id) {
        //根据id查询订单
        Orders orders = orderMapper.selectById(id);
        //当订单存在且状态为派送中时才可派送
        if (orders == null || orders.getStatus() != 4){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.selectById(id.intValue());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
